/**
 * HzSparrowAI 主要JavaScript文件
 * 处理聊天功能、文件上传、知识库交互等核心功能
 */

// 全局变量
let currentSessionId = null;
let conversationHistory = [];
let selectedFile = null;
let currentAttachedFile = null;
let currentThinkingOption = null;
let currentKnowledgeBaseId = null;
let isR1Enabled = false;
let isWebSearchEnabled = false;

// 当文档加载完成时初始化Markdown解析器
document.addEventListener('DOMContentLoaded', function() {
    // 配置marked选项
    marked.setOptions({
        breaks: true, // 支持GitHub风格的换行符
        gfm: true,    // 支持GitHub风格的Markdown
    });
});

// 监听模块加载完成事件，然后初始化UI组件
document.addEventListener('modulesLoaded', function() {
    
    initializeUIComponents();
});

/**
 * 初始化UI组件
 * 在模块加载完成后调用
 */
function initializeUIComponents() {
    // 检查用户是否已登录
    const token = localStorage.getItem('token');
    if (!token) {
        window.location.href = 'login.html';
        return;
    }
    
    // 显示用户信息
    displayUserInfo();
    
    // 初始化输入框自动调整高度
    initializeTextArea();
    
    // 初始化工具菜单
    initializeToolsMenu();
    
    // 初始化思考选项
    setupThinkingOptions();
    
    // 初始化侧边栏切换
    initializeSidebarToggle();
    
    // 初始化页签切换
    initializeTabs();
    
    // 加载对话列表
    loadConversations();
    
    // 初始化知识库选择器
    initKnowledgeBaseSelector();
    
    
}

/**
 * 显示用户信息
 */
function displayUserInfo() {
    const username = localStorage.getItem('username');
    const nickname = localStorage.getItem('nickname') || username;
    const usernameDisplay = document.getElementById('username-display');
    
    if (nickname && usernameDisplay) {
        usernameDisplay.innerHTML = `<i class="bi bi-person-circle"></i><span>${nickname}</span>`;
    }
}

/**
 * 初始化文本输入框
 */
function initializeTextArea() {
    const textArea = document.getElementById('user-input');
    if (!textArea) {
        
        return;
    }
    
    // 自动调整输入框高度
    textArea.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight) + 'px';
        // 限制最大高度
        if (parseInt(this.style.height) > 150) {
            this.style.height = '150px';
        }
    });
    
    // 键盘快捷键处理发送消息
    textArea.addEventListener('keydown', function(e) {
        // Enter发送，但Shift+Enter换行
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });
}

/**
 * 初始化工具菜单
 */
function initializeToolsMenu() {
    const toolsMenuBtn = document.getElementById('tools-menu-btn');
    const toolsMenu = document.getElementById('tools-menu');
    
    if (!toolsMenuBtn || !toolsMenu) {
        
        return;
    }
    
    toolsMenuBtn.addEventListener('click', function(e) {
        e.stopPropagation();
        toolsMenu.classList.toggle('active');
    });
    
    // 点击页面其他区域关闭菜单
    document.addEventListener('click', function(e) {
        if (e.target !== toolsMenuBtn && !toolsMenu.contains(e.target)) {
            toolsMenu.classList.remove('active');
        }
    });
}

/**
 * 初始化侧边栏切换
 */
function initializeSidebarToggle() {
    const sidebarToggle = document.querySelector('.toggle-sidebar-btn');
    if (!sidebarToggle) {
        
        return;
    }
    
    sidebarToggle.addEventListener('click', function() {
        const sidebar = document.querySelector('.sidebar');
        if (sidebar) {
            sidebar.classList.toggle('active');
        }
    });
}

/**
 * 初始化页签切换
 */
function initializeTabs() {
    const chatTabs = document.querySelectorAll('.chat-tab');
    if (chatTabs.length === 0) {
        
        return;
    }
    
    chatTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 移除所有页签的active类
            chatTabs.forEach(t => t.classList.remove('active'));
            // 添加当前页签的active类
            this.classList.add('active');
            
            // 获取页签对应的内容区域
            const tabId = this.getAttribute('data-tab');
            
            // 隐藏所有内容容器
            const containers = [
                'chat-container',
                'knowledge-container', 
                'documents-container',
                'doc-content-container',
                'add-document-container',
                'settings-container'
            ];
            
            containers.forEach(containerId => {
                const container = document.getElementById(containerId);
                if (container) {
                    container.style.display = 'none';
                }
            });
            
            // 显示对应的内容容器
            let targetContainer = null;
            if (tabId === 'chat') {
                targetContainer = document.getElementById('chat-container');
            } else if (tabId === 'knowledge') {
                targetContainer = document.getElementById('knowledge-container');
                // 如果切换到知识库页签，加载知识库列表
                loadKnowledgeBases();
            } else if (tabId === 'settings') {
                targetContainer = document.getElementById('settings-container');
                // 如果切换到设置页签，初始化设置页面
                if (typeof initSettingsPage === 'function') {
                    initSettingsPage();
                }
            }
            
            if (targetContainer) {
                // 根据页面类型设置合适的display属性
                if (tabId === 'settings') {
                    targetContainer.style.display = 'flex';
                } else if (tabId === 'knowledge') {
                    targetContainer.style.display = 'flex';
                } else {
                    targetContainer.style.display = 'block';
                }
            }
        });
    });
}

/**
 * 应用程序完全初始化后的回调函数
 * 用于其他脚本文件调用
 */
function initializeAppAfterModulesLoaded() {
    
    // 这里可以添加其他需要在模块加载完成后执行的初始化代码
}

// 退出登录
function logout() {
    localStorage.removeItem('token');
    localStorage.removeItem('username');
    localStorage.removeItem('role');
    window.location.href = 'login.html';
}

// 显示通知
function showNotification(message, type = 'success') {
    const notification = document.getElementById('notification');
    if (!notification) {
        
        return;
    }
    
    // 设置通知类型样式
    notification.className = 'notification';
    if (type === 'error') {
        notification.classList.add('notification-error');
    } else if (type === 'warning') {
        notification.classList.add('notification-warning');
    } else {
        notification.classList.add('notification-success');
    }
    
    notification.textContent = message;
    notification.style.transform = 'translateX(0)';
    
    setTimeout(() => {
        notification.style.transform = 'translateX(150%)';
    }, 3000);
}

// 清空聊天记录
function clearChat() {
    const chatOutput = document.getElementById('chat-output');
    const toolsMenu = document.getElementById('tools-menu');
    
    if (chatOutput) {
        chatOutput.innerHTML = '';
    }
    
    if (toolsMenu) {
        toolsMenu.classList.remove('active');
    }
    
    showNotification('聊天记录已清空', 'success');
}

// 复制文本到剪贴板
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        showNotification('已复制到剪贴板');
    }).catch(err => {
        
    });
}

// 切换思考过程显示
function toggleThinking(element) {
    const thinkContent = element.nextElementSibling;
    const isExpanded = element.classList.contains('active');
    
    if (isExpanded) {
        // 收起
        element.classList.remove('active');
        thinkContent.style.display = 'none';
        thinkContent.classList.remove('expanding');
    } else {
        // 展开
        element.classList.add('active');
        thinkContent.style.display = 'block';
        thinkContent.classList.add('expanding');
        
        // 移除动画类，准备下次使用
        setTimeout(() => {
            thinkContent.classList.remove('expanding');
        }, 300);
    }
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString();
}

// 加载用户的对话列表
async function loadConversations() {
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            return;
        }
        
        const response = await fetch('/api/conversation/list', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            const conversations = await response.json();
            const container = document.getElementById('conversation-items');
            
            if (!container) {
                
                return;
            }
            
            container.innerHTML = '';
            
            if (conversations.length === 0) {
                container.innerHTML = `
                    <div class="empty-placeholder">
                        <i class="bi bi-chat-square-text"></i>
                        <p>暂无对话记录</p>
                        <p class="hint">点击"开始新对话"开始聊天</p>
                    </div>
                `;
                return;
            }
            
            // 显示每个对话
            conversations.forEach(conversation => {
                displayConversationItem(conversation, container);
            });
        }
    } catch (error) {
        
    }
}

// 显示对话项
function displayConversationItem(conversation, container) {
    // 创建格式化的时间
    const timestamp = new Date(conversation.updateTime || conversation.createTime);
    const formattedDate = timestamp.toLocaleDateString();
    
    // 创建会话项
    const item = document.createElement('div');
    item.className = `conversation-item ${conversation.sessionId === currentSessionId ? 'active' : ''}`;
    item.setAttribute('data-session-id', conversation.sessionId);
    item.setAttribute('data-id', conversation.id);
    
    const title = conversation.title || '新对话';
    item.innerHTML = `
        <div class="conversation-item-content">
            <i class="bi bi-chat-text"></i>
            <span>${title}</span>
        </div>
        <button class="delete-conversation-btn" title="删除对话">
            <i class="bi bi-trash"></i>
        </button>
    `;
    
    // 添加删除按钮点击事件
    const deleteBtn = item.querySelector('.delete-conversation-btn');
    deleteBtn.addEventListener('click', (e) => {
        e.stopPropagation(); // 阻止事件冒泡
        if (confirm('确定要删除此对话吗？此操作不可恢复。')) {
            deleteConversation(conversation.id);
        }
    });
    
    // 添加点击事件，加载对话历史
    item.addEventListener('click', () => loadConversationHistory(conversation.sessionId));
    
    container.appendChild(item);
}

// 删除对话
async function deleteConversation(conversationId) {
    try {
        const token = localStorage.getItem('token');
        const response = await fetch(`/api/conversation/${conversationId}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            }
        });

        if (response.ok) {
            // 从DOM中移除对话项
            const item = document.querySelector(`.conversation-item[data-id="${conversationId}"]`);
            if (item) {
                const isCurrentSession = item.classList.contains('active');
                item.remove();
                
                // 如果删除的是当前会话，重置状态而不是创建新会话
                if (isCurrentSession) {
                    // 重置当前会话ID
                    currentSessionId = null;
                    
                    // 清空聊天区域
                    clearChat();
                    
                    // 重置知识库选择器
                    currentKnowledgeBaseId = null;
                    const kbSelector = document.getElementById('kb-selector');
                    if (kbSelector) {
                        kbSelector.value = '';
                    }
                    
                    // 重置输入框提示
                    const userInput = document.getElementById('user-input');
                    if (userInput) {
                        userInput.placeholder = '给 HzSparrowAI 发送消息';
                    }
                    
                    // 更新UI状态
                    updateActiveConversation();
                }
                
                showNotification('对话已删除', 'success');
            }
        } else {
            
            showNotification('删除对话失败', 'error');
        }
    } catch (error) {
        
        showNotification('删除对话出错', 'error');
    }
}

// 创建新对话
async function createNewConversation() {
    try {
        const token = localStorage.getItem('token');
        
        if (!token) {
            showNotification('您需要登录才能创建新对话', 'error');
            return;
        }
        
        // 生成新的会话ID
        const sessionId = generateUUID();
        
        // 创建新对话
        const response = await fetch('/api/conversation/create', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                sessionId: sessionId,
                title: '新对话',
                knowledgeBaseId: currentKnowledgeBaseId // 传递当前选择的知识库ID
            })
        });
        
        if (response.ok) {
            const conversation = await response.json();
            
            // 设置当前会话ID
            currentSessionId = conversation.sessionId;
            
            // 清空聊天区域
            clearChat();
            
            // 更新UI，高亮当前会话
            updateActiveConversation();
            
            // 刷新对话列表
            loadConversations();
            
            // 将焦点放在输入框上
            const userInput = document.getElementById('user-input');
            if (userInput) {
                userInput.focus();
                
                // 更新输入框提示文字
                if (currentKnowledgeBaseId) {
                    const kbSelector = document.getElementById('kb-selector');
                    if (kbSelector && kbSelector.selectedIndex >= 0) {
                        const kbName = kbSelector.options[kbSelector.selectedIndex].text;
                        userInput.placeholder = `向 ${kbName} 提问...`;
                    } else {
                        userInput.placeholder = '给 HzSparrowAI 发送消息';
                    }
                } else {
                    userInput.placeholder = '给 HzSparrowAI 发送消息';
                }
            }
            
            // 通知用户
            showNotification('已创建新对话', 'success');
            return conversation; // 返回创建的对话信息
        } else {
            const errorMsg = '创建对话失败';
            showNotification(errorMsg, 'error');
            throw new Error(errorMsg);
        }
    } catch (error) {
        
        showNotification('创建新对话失败', 'error');
        throw error; // 重新抛出错误
    }
}

// 加载对话历史
async function loadConversationHistory(sessionId) {
    if (currentSessionId === sessionId) return;
    
    try {
        const token = localStorage.getItem('token');
        
        // 获取会话信息
        const conversationResponse = await fetch(`/api/conversation/session/${sessionId}`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (!conversationResponse.ok) {
            throw new Error('获取会话信息失败');
        }
        
        // 解析会话信息
        const conversationData = await conversationResponse.json();
        
        // 设置当前会话ID
        currentSessionId = sessionId;
        
        // 设置知识库ID
        currentKnowledgeBaseId = conversationData.knowledgeBaseId;
        
        // 更新知识库选择器
        if (currentKnowledgeBaseId) {
            const kbSelector = document.getElementById('kb-selector');
            if (kbSelector) {
                kbSelector.value = currentKnowledgeBaseId;
                
                // 更新输入框提示
                const userInput = document.getElementById('user-input');
                if (userInput) {
                    const kbName = kbSelector.options[kbSelector.selectedIndex].text;
                    userInput.placeholder = `向 ${kbName} 提问...`;
                }
            }
        } else {
            // 重置知识库选择器
            const kbSelector = document.getElementById('kb-selector');
            if (kbSelector) {
                kbSelector.value = '';
                
                // 重置输入框提示
                const userInput = document.getElementById('user-input');
                if (userInput) {
                    userInput.placeholder = '给 HzSparrowAI 发送消息';
                }
            }
        }
        
        // 更新UI，高亮当前会话
        updateActiveConversation();
        
        // 清空当前聊天区域
        clearChat();
        
        // 获取历史记录
        const response = await fetch(`/api/chat-history/session/${sessionId}?page=1&size=100`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (!response.ok) {
            throw new Error('获取聊天历史失败');
        }
        
        const data = await response.json();
        const chatOutput = document.getElementById('chat-output');
        
        if (data.records && data.records.length > 0) {
            // 按时间顺序显示消息
            data.records.forEach(record => {
                // 添加用户消息
                chatOutput.innerHTML += `<div class="message user-message">${record.userMessage}</div>`;
                
                // 添加AI回复
                let parsedResponse = marked.parse(record.aiResponse);
                
                // 处理思考过程标签
                parsedResponse = parsedResponse.replace(/<think>([\s\S]*?)<\/think>/g, 
                    '<div class="think-container"><div class="think-toggle" onclick="toggleThinking(this)"><button class="copy-btn" onclick="event.stopPropagation(); copyToClipboard(this.closest(\'.ai-message\').textContent)" title="复制回答"><i class="bi bi-clipboard"></i></button>思考 <i class="bi bi-chevron-down"></i></div><div class="think-content markdown-content">$1</div></div>');
                
                // 添加AI消息，包含复制按钮
                chatOutput.innerHTML += `
                    <div class="message ai-message">
                        <div class="markdown-content">${parsedResponse}</div>
                    </div>
                `;
            });
            
            // 滚动到底部
            chatOutput.scrollTop = chatOutput.scrollHeight;
        }
    } catch (error) {
        
        showNotification('加载对话历史失败', 'error');
    }
}

// 更新活跃会话的UI
function updateActiveConversation() {
    const items = document.querySelectorAll('.conversation-item');
    items.forEach(item => {
        if (item.getAttribute('data-session-id') === currentSessionId) {
            item.classList.add('active');
        } else {
            item.classList.remove('active');
        }
    });
}

// 生成UUID
function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

// 打开文件上传对话框
function openFileUpload() {
    // 创建隐藏的文件输入元素
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = '.txt,.pdf,.doc,.docx,.xls,.xlsx,.csv,.md,.json';
    fileInput.style.display = 'none';
    document.body.appendChild(fileInput);
    
    // 监听文件选择
    fileInput.onchange = function(event) {
        const file = event.target.files[0];
        if (!file) return;
        
        // 检查文件大小（限制为20MB）
        if (file.size > 20 * 1024 * 1024) {
            showNotification('文件大小不能超过20MB', 'error');
            return;
        }
        
        handleSelectedFile(file);
        
        // 移除临时创建的文件输入元素
        document.body.removeChild(fileInput);
    };
    
    // 触发文件选择对话框
    fileInput.click();
}

// 处理选择的文件
function handleSelectedFile(file) {
    // 保存当前文件
    currentAttachedFile = file;
    
    // 显示文件信息
    const attachedFiles = document.getElementById('attached-files');
    const fileName = document.getElementById('attached-file-name');
    const fileSize = document.getElementById('attached-file-size');
    const fileIcon = document.querySelector('.file-icon i');
    
    // 设置文件图标
    fileIcon.className = getFileIcon(file.name);
    
    fileName.textContent = file.name;
    fileSize.textContent = formatFileSize(file.size);
    attachedFiles.style.display = 'block';
    
    // 清空输入框，聚焦以便用户输入问题
    const userInput = document.getElementById('user-input');
    userInput.value = '';
    userInput.focus();
    userInput.placeholder = '输入问题以引用文件内容...';
    
    // 添加思考选项的点击事件
    setupThinkingOptions();
    
    // 显示成功提示
    showNotification('文件已附加', 'success');
}

// 根据文件扩展名获取合适的图标
function getFileIcon(fileName) {
    const extension = fileName.split('.').pop().toLowerCase();
    
    // 文本文件
    if (['txt', 'md', 'markdown'].includes(extension)) {
        return 'bi bi-file-text';
    }
    // 文档文件
    else if (['doc', 'docx', 'rtf'].includes(extension)) {
        return 'bi bi-file-earmark-word';
    }
    // PDF文件
    else if (extension === 'pdf') {
        return 'bi bi-file-earmark-pdf';
    }
    // 电子表格
    else if (['xls', 'xlsx', 'csv'].includes(extension)) {
        return 'bi bi-file-earmark-spreadsheet';
    }
    // 代码文件
    else if (['json', 'xml', 'html', 'css', 'js'].includes(extension)) {
        return 'bi bi-file-earmark-code';
    }
    // 图片文件
    else if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg'].includes(extension)) {
        return 'bi bi-file-earmark-image';
    }
    // 压缩文件
    else if (['zip', 'rar', '7z', 'tar', 'gz'].includes(extension)) {
        return 'bi bi-file-earmark-zip';
    }
    // 默认图标
    else {
        return 'bi bi-file-earmark';
    }
}

// 格式化文件大小显示
function formatFileSize(bytes) {
    if (bytes < 1024) {
        return bytes + ' B';
    } else if (bytes < 1024 * 1024) {
        return (bytes / 1024).toFixed(2) + ' KB';
    } else {
        return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
    }
}

// 设置思考选项的点击事件
function setupThinkingOptions() {
    const options = document.querySelectorAll('.thinking-option');
    if (options.length === 0) {
        
        return;
    }
    
    options.forEach(option => {
        option.addEventListener('click', function() {
            // 移除所有选项的活动状态
            options.forEach(opt => opt.classList.remove('active'));
            // 添加当前选项的活动状态
            this.classList.add('active');
            // 保存当前选项
            currentThinkingOption = this.getAttribute('data-option');
        });
    });
}

// 移除附加的文件
function removeAttachedFile() {
    // 重置全局变量
    currentAttachedFile = null;
    currentThinkingOption = null;
    
    // 隐藏附件区域
    const attachedFiles = document.getElementById('attached-files');
    if (attachedFiles) {
        attachedFiles.style.display = 'none';
    }
    
    // 重置思考选项
    const options = document.querySelectorAll('.thinking-option');
    options.forEach(option => option.classList.remove('active'));
    
    // 重置输入框的占位符
    const userInput = document.getElementById('user-input');
    if (userInput) {
        userInput.placeholder = '给 HzSparrowAI 发送消息';
    }
    
    showNotification('已移除附加文件', 'success');
}

// 修改发送消息函数，添加文件引用功能
async function sendMessage() {
    const input = document.getElementById('user-input');
    if (!input) {
        
        return;
    }
    
    const message = input.value.trim();
    input.value = '';
    input.style.height = 'auto';
    
    if (!message && !currentAttachedFile) return;
    
    // 确保有会话ID，如果没有则等待创建完成
    if (!currentSessionId) {
        try {
            await createNewConversation();
            // 等待一下确保DOM更新完成
            await new Promise(resolve => setTimeout(resolve, 100));
        } catch (error) {
            
            showNotification('创建会话失败，请重试', 'error');
            return;
        }
    }
    
    // 再次检查会话ID
    if (!currentSessionId) {
        showNotification('无法创建会话，请刷新页面重试', 'error');
        return;
    }
    
    // 获取JWT令牌
    const token = localStorage.getItem('token');
    if (!token) {
        showNotification('您需要登录才能发送消息', 'error');
        return;
    }
    
    const chatOutput = document.getElementById('chat-output');
    if (!chatOutput) {
        
        return;
    }
    
    // 如果有附加文件，显示文件信息
    let displayMessage = message;
    if (currentAttachedFile) {
        const fileName = currentAttachedFile.name;
        
        // 显示在聊天界面
        if (message) {
            displayMessage = `${message}\n\n[附件: ${fileName}]`;
        } else {
            displayMessage = `[附件: ${fileName}]`;
        }
    }
    
    chatOutput.innerHTML += `<div class="message user-message">${displayMessage}</div>`;
    
    const aiMessageId = Date.now();
    chatOutput.innerHTML += `<div id="ai-msg-${aiMessageId}" class="message ai-message">
        <div class="loading-container">
            <div class="loading-spinner"></div>
            <span id="thinking-text-${aiMessageId}">AI正在深度思考</span>
        </div>
    </div>`;
    chatOutput.scrollTop = chatOutput.scrollHeight;
    
    // 创建思考文字轮换效果
    const thinkingTexts = [
        'AI正在深度思考',
        '正在分析您的问题',
        '搜索相关知识',
        '整理思路中',
        '生成回答中'
    ];
    let textIndex = 0;
    const thinkingTextElement = document.getElementById(`thinking-text-${aiMessageId}`);
    
    const thinkingInterval = setInterval(() => {
        if (thinkingTextElement) {
            textIndex = (textIndex + 1) % thinkingTexts.length;
            thinkingTextElement.textContent = thinkingTexts[textIndex];
        }
    }, 2000);
    
    // 获取思考选项
    const activeOption = document.querySelector('.thinking-option.active');
    const thinkingOption = activeOption ? activeOption.getAttribute('data-option') : null;
    
    try {
        // 准备发送的数据
        let url = `/api/chat?message=${encodeURIComponent(message)}&sessionId=${currentSessionId}`;
        
        // 如果有思考选项，添加到URL
        if (thinkingOption) {
            url += `&thinkingOption=${thinkingOption}`;
        }
        
        // 如果选择了知识库，添加知识库ID
        if (currentKnowledgeBaseId) {
            url += `&knowledgeBaseId=${currentKnowledgeBaseId}`;
        }
        
        // 如果有附加文件，准备表单数据
        let fetchOptions = {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        };
        
        if (currentAttachedFile) {
            const formData = new FormData();
            formData.append('file', currentAttachedFile);
            
            // 表单中添加其他参数
            formData.append('message', message);
            formData.append('sessionId', currentSessionId);
            if (thinkingOption) {
                formData.append('thinkingOption', thinkingOption);
            }
            // 添加知识库ID
            if (currentKnowledgeBaseId) {
                formData.append('knowledgeBaseId', currentKnowledgeBaseId);
            }
            
            fetchOptions = {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                body: formData
            };
            
            url = '/api/chat/with-file';
        }
        
        const response = await fetch(url, fetchOptions);
        
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        
        let aiResponse = '';
        let hasThinkSection = false;
        let thinkCompleted = false;
        
        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            
            const chunk = decoder.decode(value, { stream: true });
            aiResponse += chunk;
            
            // 检查是否包含think标签
            const hasThinkStart = aiResponse.includes('<think>');
            const hasThinkEnd = aiResponse.includes('</think>');
            
            // 更新AI回复
            const aiMsg = document.getElementById(`ai-msg-${aiMessageId}`);
            if (!aiMsg) {
                
                continue;
            }
            
            // 如果首次检测到think标签，创建思考过程容器
            if (hasThinkStart && !hasThinkSection) {
                hasThinkSection = true;
                // 创建思考过程占位符，保持动画，默认展开
                const thinkPlaceholder = '<div class="think-container"><div class="think-toggle thinking active" onclick="toggleThinking(this)"><button class="copy-btn" onclick="event.stopPropagation(); copyToClipboard(this.closest(\'.ai-message\').textContent)" title="复制回答"><i class="bi bi-clipboard"></i></button>思考 <i class="bi bi-chevron-down"></i></div><div class="think-content markdown-content" style="display: block;">正在思考中...</div></div>';
                aiMsg.innerHTML = `<div class="markdown-content">${thinkPlaceholder}<div class="ai-response-content"></div></div>`;
            }
            
            // 如果think标签完成，停止动画并折叠
            if (hasThinkEnd && !thinkCompleted) {
                thinkCompleted = true;
                // 提取think内容
                const thinkMatch = aiResponse.match(/<think>([\s\S]*?)<\/think>/);
                if (thinkMatch) {
                    const thinkContent = thinkMatch[1];
                    
                    // 更新思考内容
                    const thinkContentElement = aiMsg.querySelector('.think-content');
                    if (thinkContentElement) {
                        thinkContentElement.innerHTML = marked.parse(thinkContent);
                    }
                    
                    // 停止动画并折叠
                    const thinkToggle = aiMsg.querySelector('.think-toggle');
                    if (thinkToggle) {
                        thinkToggle.classList.remove('thinking', 'active');
                        thinkContentElement.style.display = 'none';
                    }
                }
            }
            
            // 如果think正在进行中，实时更新思考内容
            if (hasThinkStart && !hasThinkEnd) {
                const thinkMatch = aiResponse.match(/<think>([\s\S]*?)$/);
                if (thinkMatch) {
                    const thinkContent = thinkMatch[1];
                    const thinkContentElement = aiMsg.querySelector('.think-content');
                    if (thinkContentElement) {
                        thinkContentElement.innerHTML = marked.parse(thinkContent) || '正在思考中...';
                    }
                }
            }
            
            // 更新AI回答内容（think标签之外的内容）
            let nonThinkContent = '';
            if (hasThinkEnd) {
                // think已完成，移除完整的think标签
                nonThinkContent = aiResponse.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
            } else if (hasThinkStart) {
                // think进行中，移除未完成的think标签
                nonThinkContent = aiResponse.replace(/<think>[\s\S]*$/g, '').trim();
            } else {
                // 没有think标签
                nonThinkContent = aiResponse.trim();
            }
            
            if (nonThinkContent) {
                const responseContentElement = aiMsg.querySelector('.ai-response-content');
                if (responseContentElement) {
                    responseContentElement.innerHTML = marked.parse(nonThinkContent);
                } else if (!hasThinkStart) {
                    // 没有think标签，正常更新
                    aiMsg.innerHTML = `<div class="markdown-content">${marked.parse(aiResponse)}</div>`;
                }
            }
            
            chatOutput.scrollTop = chatOutput.scrollHeight;
        }
        
        // 清理思考文字轮换定时器
        clearInterval(thinkingInterval);
        
        // 移除加载指示器
        const aiMsg = document.getElementById(`ai-msg-${aiMessageId}`);
        if (aiMsg) {
            const loadingElement = aiMsg.querySelector('.loading-container');
            if (loadingElement) {
                loadingElement.remove();
            }
        }
        
        // 更新对话列表
        setTimeout(() => loadConversations(), 1500);
        
        // 消息发送后清除附加文件
        if (currentAttachedFile) {
            removeAttachedFile();
        }
        
    } catch (error) {
        
        
        // 清理思考文字轮换定时器
        clearInterval(thinkingInterval);
        
        const aiMsg = document.getElementById(`ai-msg-${aiMessageId}`);
        if (aiMsg) {
            aiMsg.innerHTML = '<div class="error-message">抱歉，请求失败。请重试。</div>';
        }
    }
}

// 导出对话
function exportChat() {
    const chatOutput = document.getElementById('chat-output');
    if (!chatOutput) {
        
        showNotification('无法导出对话：页面元素未找到', 'error');
        return;
    }
    
    const messages = chatOutput.querySelectorAll('.message');
    let content = '';
    
    messages.forEach(message => {
        if (message.classList.contains('user-message')) {
            content += `用户: ${message.textContent}\n\n`;
        } else if (message.classList.contains('ai-message')) {
            content += `AI: ${message.textContent}\n\n`;
        }
    });
    
    if (content) {
        const blob = new Blob([content], { type: 'text/plain' });
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = `对话记录_${new Date().toISOString().slice(0, 10)}.txt`;
        a.click();
        
        const toolsMenu = document.getElementById('tools-menu');
        if (toolsMenu) {
            toolsMenu.classList.remove('active');
        }
        showNotification('对话已导出', 'success');
    } else {
        showNotification('没有对话内容可导出', 'warning');
    }
}

// 分享对话
function shareChat() {
    // 这里可以实现分享功能，例如生成链接等
    showNotification('分享功能即将推出', 'info');
    document.getElementById('tools-menu').classList.remove('active');
}

// 初始化知识库选择器
async function initKnowledgeBaseSelector() {
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            
            return;
        }
        
        const response = await fetch('/api/knowledge-base/list', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            const knowledgeBases = await response.json();
            populateKnowledgeBaseSelector(knowledgeBases);
        } else {
            
        }
    } catch (error) {
        
    }
}

// 填充知识库选择器
function populateKnowledgeBaseSelector(knowledgeBases) {
    const selector = document.getElementById('kb-selector');
    if (!selector) return;
    
    // 保存当前选择的值
    const currentValue = selector.value;
    
    // 清除现有选项，保留"默认对话"选项
    selector.innerHTML = '<option value="">默认对话</option>';
    
    // 添加知识库选项
    knowledgeBases.forEach(kb => {
        const option = document.createElement('option');
        option.value = kb.id;
        option.textContent = kb.name;
        selector.appendChild(option);
    });
    
    // 恢复之前的选择
    if (currentValue) {
        selector.value = currentValue;
    }
    
    // 移除旧的事件监听器（如果存在）并添加新的
    selector.removeEventListener('change', handleKnowledgeBaseSelection);
    selector.addEventListener('change', handleKnowledgeBaseSelection);
}

// 处理知识库选择
function handleKnowledgeBaseSelection() {
    const kbSelector = document.getElementById('kb-selector');
    const selectedKbId = kbSelector.value;
    
    // 保存当前选择的知识库ID到全局变量
    currentKnowledgeBaseId = selectedKbId;
    window.currentKnowledgeBaseId = selectedKbId; // 同步到window对象
    
    // 更新输入框提示
    const input = document.getElementById('user-input');
    if (selectedKbId) {
        const kbName = kbSelector.options[kbSelector.selectedIndex].text;
        input.placeholder = `向 ${kbName} 提问...`;
    } else {
        input.placeholder = '给 HzSparrowAI 发送消息';
    }
}

function isGuestUser() {
    const token = localStorage.getItem('token');
    return !token || token === 'guest';
}

// 切换侧边栏显示状态
function toggleSidebar() {
    const sidebar = document.querySelector('.sidebar');
    sidebar.classList.toggle('active');
}